// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// E [author] rhyme_lph
// c [email]  rhymelph@gmail.com
// t [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/src/entities/employee_contact_entity.dart';
import 'package:finance_app/src/http_service/http_employee_contact_service.dart';
import 'package:finance_app/src/mixin/format_group_map_mixin.dart';
import 'package:finance_app/src/mixin/search_data_list_mixin.dart';
import 'package:finance_app/src/mixin/search_data_map_mixin.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/utils/reg_exp_utils.dart';
import 'dart:async';

import 'package:flutter/cupertino.dart';

class DuplicateAsNewProvider extends BaseProvider<List<EmployeeContactEntity>>
    with SearchDataListMixin, FormatGroupMapLocalMixin<EmployeeContactEntity> {
  EmployeeContactEntity currentSelect;

  @override
  Future get dataFuture => HttpEmployeeContactService.contactList('closed');

  @override
  FutureOr<List<EmployeeContactEntity>> transformData(
      List<EmployeeContactEntity> d, bool isCache) async {
    groupMap.clear();
    contactToMap(d);
    return d;
  }

  void contactToMap(List<EmployeeContactEntity> list) {
    sortGroupToMap(list,
        sort: (a, b) => a.name.compareTo(b.name),
        group: (a) => groupFirstName(a, (t) => t.name),
        filter: _onFilter);
  }

  void onSelectEmployee(EmployeeContactEntity data) {
    if (data != currentSelect) {
      currentSelect = data;
      update();
    }
  }

  void onCancel() {
    obtainContext?.call((context) {
      Navigator.of(context).pop();
    });
  }

  void onDuplicate() {
    if (currentSelect == null) return;
    Routes.navigateTo(RouterGenProviders.newEmployeePage, params: {
      'data': currentSelect,
      'isDuplicate': true,
    });
  }

  @override
  void searchRefreshData(searchData) {
    transformData(data, false);
    update();
  }

  bool _onFilter(EmployeeContactEntity a) {
    if (RegExpUtils.getSearchRegExp(searchController.text).hasMatch(a.name)) {
      return true;
    }
    return false;
  }
}
